// 引入mockjs
import Mock from "mockjs";
// SIM卡管理数据
let simCardList = Mock.mock({
  "list|50": [
    {
      key: "@increment(1)",
      msisdn: /^1[3-9]\d{10}$/, // MSISDN号码
      iccid: /^8986\d{16}$/, // ICCID卡号
      imsi: /^460\d{12}$/, // IMSI号码
      cardStatus: '@pick(["已激活", "已停机", "未激活", "已注销"])', // 卡状态
      channel:
        '@pick(["移动NB", "联通NB", "电信NB", "移动4G", "联通4G", "电信4G"])', // 通道
      company: '@pick(["总企业", "分公司A", "分公司B", "子公司C"])', // 所属公司
      tariffGroup:
        '@pick(["大王卡", "地王卡", "流量卡", "语音卡", "物联网卡"])', // 资费组
      usage: "@integer(0, 100)", // 用量(MB)
      activationDate: '@date("yyyy-MM-dd")', // 激活日期
      expirationDate: '@date("yyyy-MM-dd")', // 到期日期
      balance: "@integer(0, 1000)", // 余额
      remarks: '@pick(["正常使用", "测试卡", "备用卡", ""])', // 备注信息
      operator: '@pick(["中国移动", "中国联通", "中国电信"])', // 运营商
      createTime: '@datetime("yyyy-MM-dd HH:mm:ss")', // 创建时间
    },
  ],
}).list;

// 资费计划数据（用于新增时选择）
let tariffPlanList = Mock.mock({
  "list|20": [
    {
      key: "@increment(1)",
      tariffGroup:
        '@pick(["大王卡", "地王卡", "流量卡", "语音卡", "物联网卡"])', // 资费组
      planName: '@pick(["月租套餐", "流量包", "语音包", "短信包", "混合套餐"])', // 计划名称
      planAlias: '@pick(["标准版", "豪华版", "经济版", "企业版"])', // 计划别称
      tariffType: '@pick(["包月", "包年", "按量计费", "预付费"])', // 资费类型
      typeRule: '@pick(["固定", "阶梯", "封顶"])', // 类型规则
      forbiddenRechargeDate: '@date("yyyy-MM-dd")', // 禁充日期
      trafficMB: "@integer(100, 10000)", // 流量(MB)
      coefficient: "@float(0.1, 2.0, 2, 2)", // 系数
      usageMB: "@integer(50, 5000)", // 用量(MB)
      originalPrice: "@float(10, 500, 2, 2)", // 原价
      sellingPrice: "@float(8, 400, 2, 2)", // 售价
      cost: "@float(5, 300, 2, 2)", // 成本
      planPeriod: "@integer(1, 12)", // 计划周期
      periodRule: '@pick(["月", "季", "年", "日"])', // 周期规则
      effectiveType: '@pick(["立即生效", "次月生效", "指定日期生效"])', // 生效类型
      wechatPayEnabled: "@boolean", // 可微信支付
      balancePayEnabled: "@boolean", // 可余额支付
      autoPayment: "@boolean", // 自动缴费
      onSale: "@boolean", // 在售
      dataCapDisconnect: "@boolean", // 达量断网
      isSplit: "@boolean", // 是否拆分
      createTime: '@datetime("yyyy-MM-dd HH:mm:ss")', // 创建时间
    },
  ],
}).list;

// 1. SIM卡列表查询接口（包含搜索和筛选功能）
Mock.mock("/api/simCardList", "post", (options) => {
  const body = JSON.parse(options.body);
  const {
    // 筛选条件
    cardStatus,
    channel,
    company,
    tariffGroup,
    operator,
    // 搜索关键词（支持MSISDN/ICCID/IMSI/虚拟编号搜索）
    keyword,
    // 时间筛选
    timeType,
    startDate,
    endDate,
    // 号段筛选
    startNumber,
    endNumber,
    // 其他筛选
    isPolling,
    reachedThreshold,
    // 分页
    page = 1,
    pageSize = 10,
  } = body;

  let filteredList = [...simCardList];

  // 筛选逻辑
  if (cardStatus) {
    filteredList = filteredList.filter(
      (item) => item.cardStatus === cardStatus
    );
  }
  if (channel) {
    filteredList = filteredList.filter((item) => item.channel === channel);
  }
  if (company) {
    filteredList = filteredList.filter((item) => item.company === company);
  }
  if (tariffGroup) {
    filteredList = filteredList.filter(
      (item) => item.tariffGroup === tariffGroup
    );
  }
  if (operator) {
    filteredList = filteredList.filter((item) => item.operator === operator);
  }

  // 关键词搜索（支持MSISDN/ICCID/IMSI模糊搜索）
  if (keyword) {
    filteredList = filteredList.filter(
      (item) =>
        item.msisdn.includes(keyword) ||
        item.iccid.includes(keyword) ||
        item.imsi.includes(keyword) ||
        item.company.includes(keyword) ||
        item.tariffGroup.includes(keyword)
    );
  }

  // 时间筛选
  if (startDate && endDate) {
    filteredList = filteredList.filter((item) => {
      const itemDate = new Date(item.activationDate);
      const start = new Date(startDate);
      const end = new Date(endDate);
      return itemDate >= start && itemDate <= end;
    });
  }

  // 分页
  const start = (page - 1) * pageSize;
  const end = start + pageSize;
  const pageData = filteredList.slice(start, end);

  return {
    code: 200,
    message: "查询成功",
    data: {
      list: pageData,
      total: filteredList.length,
      page: page,
      pageSize: pageSize,
    },
  };
});

// 2. 新增SIM卡接口
Mock.mock("/api/simCard/add", "post", (options) => {
  const body = JSON.parse(options.body);
  const newCard = {
    key: simCardList.length + 1,
    msisdn: body.msisdn || Mock.mock(/^1[3-9]\d{10}$/),
    iccid: body.iccid || Mock.mock(/^8986\d{16}$/),
    imsi: body.imsi || Mock.mock(/^460\d{12}$/),
    cardStatus: body.cardStatus || "未激活",
    channel:
      body.channel ||
      Mock.mock(
        '@pick(["移动NB", "联通NB", "电信NB", "移动4G", "联通4G", "电信4G"])'
      ),
    company:
      body.company ||
      Mock.mock('@pick(["总企业", "分公司A", "分公司B", "子公司C"])'),
    tariffGroup:
      body.tariffGroup ||
      Mock.mock('@pick(["大王卡", "地王卡", "流量卡", "语音卡", "物联网卡"])'),
    usage: body.usage || 0,
    activationDate: body.activationDate || "",
    expirationDate: body.expirationDate || "",
    balance: body.balance || 0,
    remarks: body.remarks || "",
    operator:
      body.operator || Mock.mock('@pick(["中国移动", "中国联通", "中国电信"])'),
    createTime: Mock.mock('@datetime("yyyy-MM-dd HH:mm:ss")'),
  };

  simCardList.push(newCard);

  return {
    code: 200,
    message: "新增成功",
    data: newCard,
  };
});

// 3. 资费计划列表查询接口
Mock.mock("/api/tariffPlanList", "post", (options) => {
  const body = JSON.parse(options.body);
  const {
    tariffGroup, // 资费组筛选
    planName, // 计划名称搜索
    tariffType, // 资费类型筛选
    onSale, // 在售状态筛选
    page = 1,
    pageSize = 10,
  } = body;

  let filteredList = [...tariffPlanList];

  // 筛选逻辑
  if (tariffGroup) {
    filteredList = filteredList.filter(
      (item) => item.tariffGroup === tariffGroup
    );
  }

  if (tariffType) {
    filteredList = filteredList.filter(
      (item) => item.tariffType === tariffType
    );
  }

  if (onSale !== undefined) {
    filteredList = filteredList.filter((item) => item.onSale === onSale);
  }

  // 计划名称搜索
  if (planName) {
    filteredList = filteredList.filter(
      (item) =>
        item.planName.includes(planName) || item.planAlias.includes(planName)
    );
  }

  // 分页
  const start = (page - 1) * pageSize;
  const end = start + pageSize;
  const pageData = filteredList.slice(start, end);

  return {
    code: 200,
    message: "查询成功",
    data: {
      list: pageData,
      total: filteredList.length,
      page: page,
      pageSize: pageSize,
    },
  };
});

// 4. 新增资费计划接口
Mock.mock("/api/tariffPlan/add", "post", (options) => {
  const body = JSON.parse(options.body);
  const newPlan = {
    key: tariffPlanList.length + 1,
    ...body,
    createTime: Mock.mock('@datetime("yyyy-MM-dd HH:mm:ss")'),
  };

  tariffPlanList.push(newPlan);

  return {
    code: 200,
    message: "新增成功",
    data: newPlan,
  };
});

// 5. 编辑SIM卡接口
Mock.mock("/api/simCard/edit", "post", (options) => {
  const body = JSON.parse(options.body);
  const { key, ...updateData } = body;

  const index = simCardList.findIndex((item) => item.key === key);
  if (index !== -1) {
    simCardList[index] = { ...simCardList[index], ...updateData };
    return {
      code: 200,
      message: "编辑成功",
      data: simCardList[index],
    };
  } else {
    return {
      code: 404,
      message: "数据不存在",
    };
  }
});

// 6. 删除SIM卡接口
Mock.mock("/api/simCard/delete", "post", (options) => {
  const body = JSON.parse(options.body);
  const { key } = body;

  const index = simCardList.findIndex((item) => item.key === key);
  if (index !== -1) {
    simCardList.splice(index, 1);
    return {
      code: 200,
      message: "删除成功",
    };
  } else {
    return {
      code: 404,
      message: "数据不存在",
    };
  }
});

// 7. 获取下拉选项数据接口
Mock.mock("/api/options", "get", () => {
  return {
    code: 200,
    message: "获取成功",
    data: {
      cardStatusOptions: ["已激活", "已停机", "未激活", "已注销"],
      channelOptions: [
        "移动NB",
        "联通NB",
        "电信NB",
        "移动4G",
        "联通4G",
        "电信4G",
      ],
      companyOptions: ["总企业", "分公司A", "分公司B", "子公司C"],
      tariffGroupOptions: ["大王卡", "地王卡", "流量卡", "语音卡", "物联网卡"],
      operatorOptions: ["中国移动", "中国联通", "中国电信"],
      tariffTypeOptions: ["包月", "包年", "按量计费", "预付费"],
      periodRuleOptions: ["月", "季", "年", "日"],
      effectiveTypeOptions: ["立即生效", "次月生效", "指定日期生效"],
      timeTypeOptions: ["激活日期", "到期日期", "创建日期"],
    },
  };
});

// 获取时间轴数据接口
Mock.mock("/user/getMasterSelfBlog", "get", (options) => {
  const { pageNum = 1, pageSize = 10 } = options.url.split("?")[1].split("&").reduce((acc, cur) => {
    const [key, value] = cur.split("=");
    acc[key] = value;
    return acc;
  }, {});

  // 模拟时间轴数据
  const timelineData = Mock.mock({
    [`list|${pageSize}`]: [
      {
        id: "@increment(1)",
        title: "@ctitle(5, 15)",
        content: "@cparagraph(1, 3)",
        date: '@datetime("yyyy-MM-dd HH:mm:ss")',
        type: '@pick(["primary", "success", "warning", "error", "info"])'
      }
    ]
  });

  return {
    code: 200,
    message: "获取成功",
    data: {
      list: timelineData.list,
      total: 50,
      pageNum: parseInt(pageNum),
      pageSize: parseInt(pageSize)
    }
  };
});

export default Mock;
